package com.csj.lc.service;

import cn.hutool.crypto.SecureUtil;
import com.csj.lc.base.BaseService;
import com.csj.lc.entity.*;
import com.csj.lc.entity.dto.LayuiDTO;
import com.csj.lc.entity.dto.ReturnDTO;
import com.csj.lc.entity.dto.SearchDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
@Transactional
public class UserService extends BaseService {

    public User getCurrentUser(HttpServletRequest request){
        return (User)request.getSession().getAttribute("loginUser");
    }

    public int getCurrentUserId(HttpServletRequest request){
        return  getCurrentUser(request).getUserId();
    }

    public String detail(HttpServletRequest request, Model model) {

//        测多对一子查询（association)
//        Operation op = operationMapper.queryById(40);
//        System.out.println(op);

        // 在同一个方法内，跑同一个Mapper方法=同一个sqlSession吗？（默认情况下，一级缓存也即会话缓存是开启的）
        // 在这种情况下，就只跑一次sql代码，且封装的实体类，实际上是同一个！（若之间还执行了增删改的方法，哪怕和本查询id无关，仍会更新缓存）
//        Operation op2 = operationMapper.queryById(40);
//        System.out.println(op2);
//
//        System.out.println( op == op2);

        // 测多对一联表查询
//        List<Operation> operations = operationMapper.queryByUid(1);
//        for (Operation o:operations){
//            System.out.println(o);
//        }

        // 测 一对多 多表联查
//        User userTemp = userMapper.queryOps(1);
        // 测 一对多 子查询
//        User userTemp = userMapper.queryOps2(1);
//
//        for (Operation op : userTemp.getOps()){
//            System.out.println(op.getContent());
//        }

        //　测试　queryById（找到所有的属性，包括company和role）
        User user2 = userMapper.queryById(1);
        System.out.println(user2);

        return "user/detail";
    }

    public ReturnDTO<User> update(HttpServletRequest request, User user) {

        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(loginUser.getUserId() != user.getUserId()){
            return new ReturnDTO<User>( -1,"非当前用户无法修改用户数据！" );
        }else{
            // 只改这几项
            loginUser.setNickname(user.getNickname());
            loginUser.setRemarks(user.getRemarks());

            if(userMapper.update(loginUser)){
                return new ReturnDTO<User>( 0,"用户信息修改成功。",loginUser,null );
            }else{
                return new ReturnDTO<User>( -1,"用户信息修改更新！" );
            }
        }
    }

    public String password(HttpServletRequest request, Model model) {

       return "user/password";
    }

    public ReturnDTO<User> changePassword(HttpServletRequest request, User user) {

        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(loginUser.getUserId() != user.getUserId()){
            return new ReturnDTO<User>( -1,"非当前用户无法修改密码！" );
        }else{

            HashMap<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("user_id",loginUser.getUserId());
            paramMap.put("password",SecureUtil.md5(user.getPassword()) );

            if(userMapper.changePassword( paramMap  )){
                // 需要删除Session内的loginUser，以便用户重新登录
                request.getSession().removeAttribute("loginUser");
                return new ReturnDTO<User>( 0,"用户密码修改成功，请重新登录。",null,null );
            }else{
                return new ReturnDTO<User>( -1,"用户信息失败更新！" );
            }
        }
    }

    public String list(HttpServletRequest request, Model model, int roleId, int pageNo) {

        Role role = userMapper.getRole(roleId);
        model.addAttribute("role",role);

        return "user/list";
    }

    public LayuiDTO<User> getUserList(HttpServletRequest request, Model model,
                                      int roleId, int pageNo , int pageSize ) {

        int userCount = userMapper.getCount(roleId);
        Role role = userMapper.getRole(roleId);

        int startPos = (pageNo - 1 ) * pageSize;

        List<User> userList = userMapper.getList( roleId , startPos , pageSize );

        LayuiDTO<User> result = new LayuiDTO<User>();
        result.setCount(userCount);
        if(userList!= null && userList.size()>0 ){
            result.setCode(0);
            result.setMsg("成功获取" + role.getShowName() +"列表");
            result.setData(userList);
        }else{
            result.setCode(-1);
            result.setMsg( role.getShowName() + "列表数据为空");
            result.setData(null);
        }

        return result;
    }

    public String history(HttpServletRequest request, Model model, SearchDTO searchDTO,Boolean isDefault) {

        if(!isDefault){
            User loginUser = getCurrentUser(request);
            HashMap map = new HashMap();
            map.put("userId" , loginUser.getUserId() );
            map.put("startTime", searchDTO.getStartTime() ) ;
            map.put("endTime" , searchDTO.getEndTime());
            // 为避免SQL注入，需主动处理关键字，并进行封装
            String keyword = searchDTO.getKeyword();
            if(keyword != null && !keyword.trim().equals("") ){
                map.put("keyword", "%"+keyword+"%");
            }
            List< Operation >  opList = userMapper.queryOps( map ) ;

            model.addAttribute( "opList" , opList);
            model.addAttribute("searchDTO" ,searchDTO);
        }

        return "user/history";
    }


    public User getUserById(int userId) {
        User u = userMapper.queryById(userId);
        return u ;
    }
}
